﻿using System;
using System.Collections.Generic;
using System.Linq;
using Atmk.WaterMeter.EF;
using Atmk.WaterMeter.EF.ModelPuls;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Common;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Logic.TempLogic;
using Atmk.WaterMeter.MIS.Models;
using Atmk.WaterMeter.MIS.Models.ModelPuls;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NLog;

namespace Atmk.WaterMeter.MIS.Controllers
{
    /// <summary>
    /// 结算接口
    /// </summary>
    [Authorize]
    public class SettlementManageController : BaseApiController
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly ISettlementManageLogic _settlementManageLogic;
        private readonly IBaseInfoLogic _baseStatistcsLogic;
        private readonly TokenHelper _tokenHelper;

        /// <inheritdoc />
        public SettlementManageController(IBaseInfoLogic baseInfoLogic, ISettlementManageLogic settlementManageLogic, TokenHelper tokenHelper)
        {
            _settlementManageLogic = settlementManageLogic;
            _tokenHelper = tokenHelper;
            _baseStatistcsLogic = baseInfoLogic;
        }

        /// <summary>
        /// 结算
        /// </summary>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/Settlement/Settlement")]
        public IActionResult Settlement([FromBody] dynamic obj)
        {
            var token = _tokenHelper.GetTokenByHttpContext();
            //try
            //{
            string aid = obj.aid.ToString();
            var res = DateTime.TryParse(obj.month.ToString(), out DateTime month);
            if (!res)
                return Ok(new { errcode = 1, msg = $"结算日期格式错误" });
            int resultCount = new SettlementDAL().Settlement(token, aid, month);
            if (resultCount > 0)
            {
                return Ok(new { errcode = 0, msg = "ok", data = new { settlement = resultCount } });
            }
            else 
            {
                return Ok(new { errcode = 1, msg = $"结算数据小于0条" });
            }
            //var result =
            //_settlementManageLogic.Settlement(token.payload.id, aid, month, out int message, out Exception exception);
            //if (!result)
            //{
            //    return Ok(
            //        new
            //        {
            //            errcode = 1,
            //            msg = $"结算失败:{exception.Message}"
            //        });
            //}

            //return Ok(new
            //{
            //    errcode = 0,
            //    msg = "ok",
            //    data = new
            //    {
            //        settlement = message
            //    }
            //});
            //}
            //catch (Exception e)
            //{
            //    _logger.Error(e.Message);
            //    return Ok(new
            //    {
            //        errcode = 1,
            //        msg = $"获取扣费数据错误,错误:{e.Message}"
            //    });
            //}
        }

        private List<District> getNodeNext(List<District> districts, string id, List<District> districtsOld, List<District> result_last_District)
        {
            if (districts.Any(m => m.Id.ToString() == id && m.NodeType == 2))
            {
                result_last_District.AddRange(districts.Where(m => m.Id.ToString() == id));
            }
            else
            {
                foreach (var item in districtsOld.Where(m => m.Parent == id))
                {
                    getNodeNext(districtsOld.Where(m => m.Parent == id).ToList(), item.Id.ToString(), districtsOld, result_last_District);
                }
            }
            return result_last_District;
        }

        [HttpGet]
        public IActionResult SettlementManpower()
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var ProjectId = "434d6136-99f4-414b-bd08-02a27971bc73";
                    //所有数据未结算数据
                    var settleDays_all = _context.SettlementDay.Where(m => m.SettlementState == 0 && m.ReadTime >= DateTime.Now.AddDays(-1).Date && m.Dosage > 0).Take(10000).ToList();
                    //按表号分组
                    var total_Meter = _context.Meter.ToList();
                    var prcieStep = _context.PrcieStep.Where(m => m.ProjectId == ProjectId).FirstOrDefault();
                    var feePrice = _context.FeePrice.Where(m => prcieStep.Id == m.PiceStepId).FirstOrDefault();
                    //表用量
                    var settleDaysGroup = settleDays_all.GroupBy(m => m.CtdeviceId).Select(k =>
                        new Out_SettleDayGroup
                        {
                            meter = total_Meter.FirstOrDefault(m => m.CtdeviceId == k.Key),
                            WaterVolume = Convert.ToDecimal(k.Sum(l => l.Dosage))
                        });
                    var settleDayshasOwner = settleDaysGroup.Where(m => m.meter != null);
                    var CtdeviceIds = settleDayshasOwner.Select(m => m.meter.CtdeviceId).ToArray();
                    var settleDays_list = settleDays_all.Where(m => CtdeviceIds.Contains(m.CtdeviceId)).ToList();

                    foreach (var item in settleDayshasOwner)
                    {
                        if (item.meter != null)
                        {
                            var orderDetail = new OrderDetail();
                            orderDetail.CostType = 1; //水表扣费
                            orderDetail.RechargeChannels = "水表扣费";
                            orderDetail.WaterVolume = item.WaterVolume;
                            orderDetail.OwnerId = item.meter.OwnerId;
                            orderDetail.MeterNumber = item.meter.MeterNumber;
                            orderDetail.MeterId = item.meter.Id;
                            orderDetail.CreateTime = DateTime.Now;
                            orderDetail.WaterPrice = feePrice.Price1;
                            orderDetail.Money = -item.WaterVolume * feePrice.Price1;
                            if (orderDetail.Money < 0 && item.WaterVolume < 999)
                                _context.OrderDetail.Add(orderDetail);
                        }
                    }
                    //改变 “有业主” 该月水表的 结算状态

                    foreach (var item in settleDays_list)
                    {
                        item.SettlementState = 1;
                    }
                    _context.UpdateRange(settleDays_list);
                    var Count = _context.SaveChanges();
                    return Ok(new { errcode = 0, msg = "ok", data = new { settlement = settleDayshasOwner.Count() } });
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"人工结算失败:{ex.Message}");
                return Ok(new { errcode = 1, msg = $"人工结算失败" });
            }
        }

        /// <summary>
        /// 查询结算信息
        /// </summary>
        /// <returns></returns>
        //[HttpPost("/api/{X-Version}/Settlement/Select")]
        //public IActionResult SelectSettlement([FromBody] dynamic obj)
        //{
        //    var token = _tokenHelper.GetTokenByHttpContext();
        //    //验证用户信息
        //    //获取配置

        //    var pageSize = _baseStatistcsLogic.PageSize(token.payload.id);
        //    try
        //    {
        //        //获取所有查询条件
        //        var searchType = obj.searchType.ToString();
        //        var searchValue = obj.searchValue.ToString();
        //        var aid = obj.aid.ToString();
        //        var page = Simple.IntConvertString(obj.page.ToString());
        //        string meterType = obj.meterType.ToString();
        //        //时间--转换确认
        //        var dts = DateTime.TryParse(obj.startTime.ToString(), out DateTime startTime);
        //        var dte = DateTime.TryParse(obj.endTime.ToString(), out DateTime endTime);
        //        if (!dts || !dte)
        //        {
        //            return Ok(new
        //            {
        //                errcode = 1,
        //                msg = $"时间格式错误"
        //            });
        //        }

        //        var result = _settlementManageLogic.SelectSettlement(token.payload.id, aid, page, pageSize,
        //            meterType, startTime, endTime, out int count, searchType, searchValue);
        //        return Ok(new
        //        {
        //            errcode = 0,
        //            msg = "ok",
        //            data = new
        //            {
        //                total = count,
        //                pageSize,
        //                list = result
        //            }
        //        });
        //    }
        //    catch (Exception e)
        //    {
        //        _logger.Error(e.Message);
        //        return Ok(new
        //        {
        //            errcode = 1,
        //            msg = $"获取账户数据错误,错误:{e.Message}"
        //        });
        //    }
        //}

        /// <summary>
        /// 撤销结算
        /// </summary>
        /// <returns></returns>
        //[HttpPost("/api/{X-Version}/Settlement/Revert")]
        //public IActionResult RevertSettlement([FromBody] dynamic obj)
        //{
        //    var token = _tokenHelper.GetTokenByHttpContext();
        //    //验证用户信息

        //    try
        //    {
        //        //获取配置
        //        string userId = obj.ownerId.ToString();
        //        string settlementId = obj.settlementId.ToString();
        //        var result = _settlementManageLogic.RevertSettlement(userId, settlementId, out Exception exception);
        //        if (!result)
        //        {
        //            return Ok(
        //                new
        //                {
        //                    errcode = 1,
        //                    msg = $"撤销失败:{exception.Message}"
        //                });
        //        }

        //        return Ok(new
        //        {
        //            errcode = 0,
        //            msg = "ok"
        //        });
        //    }
        //    catch (Exception e)
        //    {
        //        _logger.Error(e.Message);
        //        return Ok(new
        //        {
        //            errcode = 1,
        //            msg = $"获取扣费数据错误,错误:{e.Message}"
        //        });
        //    }
        //}
    }
}